﻿using System;
using System.Diagnostics;
using System.IO;
using System.Reflection;

namespace ProjectAutumn.Graphics
{
    public static class GraphicsManager
    {
        internal static string GetDll(GraphicsSystems graphics)
        {
            string assembly = "ProjectAutumn.GraphicsDevice.";
            switch (graphics)
            {
                case GraphicsSystems.Direct2D:
                    assembly += "Direct2D";
                    if (Utility.IsX64()) assembly += "X64";
                    break;
                case GraphicsSystems.DirectX10:
                    assembly += "DirectX10";
                    if (Utility.IsX64()) assembly += "X64";
                    break;
                case GraphicsSystems.DirectX11:
                    assembly += "DirectX11";
                    if (Utility.IsX64()) assembly += "X64";
                    break;
                case GraphicsSystems.DirectX9:
                    assembly += "DirectX9";
                    if (Utility.IsX64()) assembly += "X64";
                    break;
                case GraphicsSystems.OpenGL:
                    assembly += "OpenGL";
                    break;
                case GraphicsSystems.SDL:
                    assembly += "SDL";
                    break;
                case GraphicsSystems.Form:
                    assembly += "Form";
                    break;
                default:
                    throw new ArgumentOutOfRangeException("graphics");
            }
            return assembly + ".dll";
        }
        public static GraphicsDevice CreateGraphics(GraphicsSystems graphics, Game game)
        {
            if (graphics == GraphicsSystems.Null) return new NullGraphics(game);
            return Utility.LoadClass(GetDll(graphics), typeof(GraphicsDevice), game) as GraphicsDevice;
        }
        public static bool Exists(GraphicsSystems graphics)
        {
            if (graphics == GraphicsSystems.Null) return true;
            string assembly = GetDll(graphics);
            if (File.Exists(assembly))
            {
                try
                {
                    Assembly.LoadFile(new FileInfo(assembly).FullName);
                    return true;
                }
                    catch(BadImageFormatException)
                {
                    return true;
                }
#if DEBUG
                catch(Exception e)
                {
                    Console.WriteLine(e);
                    Debug.WriteLine(e);
                }
#endif
                catch { }
            }
            return false;
        }
    }
}
